﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Fis.Win.Forms
{
    public partial class UserEditForm : EditForm
    {
        public UserEditForm()
        {
            InitializeComponent();
        }

        string oldPassword = string.Empty;

        public override void InitializeBinding()
        {
            var d = ViewModel["viewData"] as DataTable;
            ViewModel["Action"] = ViewState.ToString();

            if (ViewState == Agile.Engine.View.ViewState.AddNew)
            {
                d.Rows[0]["FRIGHTS"] = 0;
                d.Rows[0]["FSTATUS"] = 0;
                d.Rows[0]["SBOOKID"] = Fis.Win.Utils.AppSession.BookID;
            }
            else
                oldPassword = d.Rows[0]["FPASSWORD"].ToString();

            Fis.Win.Utils.UIUtils.ClearBindings(dataLayoutControl1);
            Fis.Win.Utils.UIUtils.TagBindings(dataLayoutControl1, d);

            Fis.Win.Utils.UIUtils.LookUpBinding(FSTATUSSpinEdit, Fis.Win.Utils.CacheContext.StateCache(), "display", "value");
            FUSERNAMETextEdit.Focus();
        }

        protected override void InitializeAfterSave()
        {
            ViewState = Agile.Engine.View.ViewState.AddNew;
            ViewModel = ViewProvider.InitializeViewModel(null);
            InitializeBinding();
        }

        protected override bool SaveProcess()
        {
            var d = ViewModel["viewData"] as DataTable;

            if (FPASSWORDTextEdit.Text.Length == 0)
            {
                Message = "密码不能为空";
                return false;
            }

            var newPassword = Agile.Engine.Utils.StringUtils.ToMD5(FPASSWORDTextEdit.Text);
            //密码修改处理
            if ((ViewState == Agile.Engine.View.ViewState.AddNew || !oldPassword.Equals(newPassword)) 
                && !oldPassword.Equals(FPASSWORDTextEdit.Text))
            {
                d.Rows[0]["FPASSWORD"] = newPassword;
            }

            ///失败
            if (!ViewProvider.ExecuteUpdate(ViewModel))
            {
                return false;
            }

            Message = "保存成功";
            return true;
        }

        public override void InitializeViewUI()
        {
            FPASSWORDTextEdit.Properties.ReadOnly = !Fis.Win.Utils.AppSession.IsAdminUser;
        }

        private void UserEditForm_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'cacheDataSet.TUSER' table. You can move, or remove it, as needed.

        }
    }
}
